import streamlit as st
from metagpt.config2 import Config
from metagpt.const import CONFIG_ROOT
from code_editor import code_editor
from metagpt.logs import logger

DEFAULT_CONFIG = """# Full Example: https://github.com/geekan/MetaGPT/blob/main/config/config2.example.yaml
# Reflected Code: https://github.com/geekan/MetaGPT/blob/main/metagpt/config2.py
# Config Docs: https://docs.deepwisdom.ai/main/en/guide/get_started/configuration.html
llm:
  api_type: "openai"  # or azure / ollama / groq etc.
  model: "glm4-chat"  # or gpt-3.5-turbo
  base_url: "https://localhost:9998/v1"  # or forward url / other llm url
  api_key: "xxxxxxx"
"""
def copy_config_to():
    """Initialize the configuration file for MetaGPT."""
    target_path = CONFIG_ROOT / "config2.yaml"

    # 创建目标目录（如果不存在）
    target_path.parent.mkdir(parents=True, exist_ok=True)

    # 如果目标文件已经存在，则重命名为 .bak
    if target_path.exists():
        # backup_path = target_path.with_suffix(".bak")
        # target_path.rename(backup_path)
        # print(f"Existing configuration file backed up at {backup_path}")
        pass
    else:
        # 复制文件
        target_path.write_text(DEFAULT_CONFIG, encoding="utf-8")
        logger.info(f"Configuration file initialized at {target_path}")

def reload():
    st.session_state["config"] = Config.default()

def show_config():
    st.title("Config")
    configTab, editorTab = st.tabs(["Config", "Editor"])
    reload()
    config = st.session_state["config"]
    with configTab:
        with st.container(border=True):
            st.subheader("Meta Config")
            st.text(f"language: {config.language}")
            st.text(f"prompt_schema: {config.prompt_schema}")
            st.text(f"workspace: {config.workspace.path}")
        with st.container():
            st.subheader("LLM Config")
            st.table(config.llm)
        with st.container():
            st.subheader("Embedding Config")
            st.table(config.embedding)
        with st.container():
            st.subheader("Search Config")
            st.table(config.search)
        st.button("reload")
        
    with editorTab:
        target_path = CONFIG_ROOT / "config2.yaml"
        with open(target_path, "r", encoding="utf-8") as file:
            editor_btns = [{
                    "name": "Save",
                    "feather": "Save",
                    "hasText": True,
                    "commands": ["save-state", ["response","saved"]],
                    "response": "saved",
                    "style": {"bottom": "calc(50% - 4.25rem)", "right": "0.4rem"}
            }]
            response_dict = code_editor(file.read(),
                                        lang="yaml", 
                                        shortcuts="vscode",
                                        focus=False, buttons=editor_btns)

            if len(response_dict['id']) != 0 and ( response_dict['type'] == "saved" ):
                target_path = CONFIG_ROOT / "config2.yaml"
                code_text = response_dict['text']
                target_path.write_text(code_text, encoding="utf-8")
                config = Config.default()
                st.session_state["config"] = config
                st.success(f"Configuration file write to {target_path}")
                

    